$(function() {
    
    var textboxes = $("input, select, textarea").not(".noenter"),
    box, currentBoxNumber;

    if ($.browser.mozilla) 
        $(textboxes).keypress(checkForEnter);
    else
        $(textboxes).keydown(checkForEnter);
    

    function checkForEnter (event) {
        
        var entrar = true;
        if (event.keyCode == 13) {
            
            currentBoxNumber = textboxes.index(this);
            
            if($(this).prop('tagName') === "TEXTAREA") {
                entrar = false;
            }
            
            if($(this).prop('type') === "submit") {
                entrar = false;
            }
            
            if($(".typeahead.dropdown-menu:visible").length > 0) {
                entrar = false;
            }
            
            if(event.ctrlKey) {
                entrar = true;
            }
            
            if(entrar) {
                if (textboxes[currentBoxNumber + 1] != null) {
                
                    box = (!event.shiftKey ? getNextSelector(currentBoxNumber) : getPrevSelector(currentBoxNumber));
                    
                    if(box !== undefined) box.focus();
                    
                    event.preventDefault();
                }	 
            }
            
        }
    } 
    
    function getNextSelector (z) {
        
        var element, nextSelector,
        max = textboxes.length;
            
        z++;
        for (var i = currentBoxNumber; i < max; i++) {
            nextSelector = textboxes[z];
            
            if($(nextSelector).is(":visible")) {
                element = $(nextSelector);
                break;
            }
            
            z++;
        }
        return element;
    }
    
    function getPrevSelector (z) {
        
        var element, nextSelector,
        max = textboxes.length;
            
        z--;
        for (var i = max; i >= currentBoxNumber; i--) {
            nextSelector = textboxes[z];
            
            if($(nextSelector).is(":visible")) {
                element = $(nextSelector);
                break;
            }
            
            z--;
        }
        return element;
    }
    
    // Gloabal
    window.updateEnterInputs = function() {
        textboxes = $("input, select, textarea").not(".noenter");
    };
    
});